from numpy import *

# 创建一些实验样本
def loadDataSet():
    postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him'],['stop', 'posting', 'stupid', 'worthless', 'garbage'],['mr', 'licks', 'ate', 'my', 'steak', 'how', 'to', 'stop', 'him'],['quit', 'buying', 'worthless', 'dog', 'food', 'stupid']]
    classVec = [0,1,0,1,0,1]    # 1 代表侮辱性文字, 0 代表正常言论
    return postingList,classVec

# 创建一个包含所有文档中出现的不重复词的列表                
def createVocabList(dataSet):
    vocabSet = set([])  # 创建一个空集
    for document in dataSet:
        vocabSet = vocabSet | set(document) # 创建两个集合的并集，操作符“|”用于求两个集合的并集
    return list(vocabSet)

# 朴素贝叶斯词集模型（set-of-words model）
def setOfWords2Vec(vocabList, inputSet):  # 输入参数，vocabList为词汇表，inputSet为某个文档
    returnVec = [0]*len(vocabList)
    for word in inputSet:     # 创建一个其中所含元素都为0的向量
        if word in vocabList:
            returnVec[vocabList.index(word)] = 1
        else: print ("the word: %s is not in my Vocabulary!" % word)
    return returnVec # 输出returnVec为文档向量，向量的每一元素为1或0，分别表示词汇表中的单词在输入文档中是否出现

# 朴素贝叶斯分类器训练函数
def trainNB0(trainMatrix,trainCategory):    # 输入参数trainMatrix为文档矩阵，trainCategory为每篇文档类别标签所构成的向量
    numTrainDocs = len(trainMatrix)         # 获取训练文档数numTrainDocs
    numWords = len(trainMatrix[0])          # 获取文档向量的长度
    pAbusive = sum(trainCategory)/float(numTrainDocs)  # 计算文档属于侮辱性文档的概率
    # 初始化概率
    #p0Num = zeros(numWords); p1Num = zeros(numWords)       # 初始化各类别的词频向量，置为0向量 
    #p0Denom = 0.0; p1Denom = 0.0                           # 初始化各类别总词数，置0
    p0Num = ones(numWords); p1Num = ones(numWords)          #change to ones() 
    p0Denom = 2.0; p1Denom = 2.0                            #change to 0.0
    for i in range(numTrainDocs):
        if trainCategory[i] == 1:
            p1Num += trainMatrix[i]             # 将所有侮辱性文档的文档向量累加，存入p1Num
            #p1Denom += 1                        # 统计侮辱性文档数，存入p1Denom
            p1Denom += sum(trainMatrix[i])      # 将所有侮辱性文档的各自的单词数累加求和，存入p1Denom
        else:
            p0Num += trainMatrix[i]             # 将所有正常文档的文档向量累加，存入p0Num
            #p0Denom += 1                        # 统计正常文档数，存入p0Denom
            p0Denom += sum(trainMatrix[i])      # 将所有正常文档的各自的单词数累加求和，存入p0Denom
    #p1Vect = p1Num/p1Denom          #计算P1向量
    #p0Vect = p0Num/p0Denom          #计算P0向量
    p1Vect = log(p1Num/p1Denom)          #change to log()
    p0Vect = log(p0Num/p0Denom)          #change to log()
    return p0Vect,p1Vect,pAbusive

# 朴素贝叶斯分类函数
def classifyNB(vec2Classify, p0Vec, p1Vec, pClass1):
    # 元素相乘，计算p(ci|w)=p(w|ci)*p(ci)/p(w)
    p1 = sum(vec2Classify * p1Vec) + log(pClass1)    
    p0 = sum(vec2Classify * p0Vec) + log(1.0 - pClass1)
    # 比较分类概率大小，判断分类
    if p1 > p0:
        return 1
    else: 
        return 0

# 朴素贝叶斯词袋模型（bag-of-words model）   
def bagOfWords2VecMN(vocabList, inputSet):
    returnVec = [0]*len(vocabList)
    for word in inputSet:
        if word in vocabList:
            returnVec[vocabList.index(word)] += 1
    return returnVec

# 封装的测试函数
def testingNB():
    listOPosts,listClasses = loadDataSet()
    myVocabList = createVocabList(listOPosts)
    trainMat=[]
    for postinDoc in listOPosts:
        trainMat.append(setOfWords2Vec(myVocabList, postinDoc))
    p0V,p1V,pAb = trainNB0(array(trainMat),array(listClasses))
    testEntry = ['love', 'my', 'dalmation']
    thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
    print (testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb))
    testEntry = ['stupid', 'garbage']
    thisDoc = array(setOfWords2Vec(myVocabList, testEntry))
    print (testEntry,'classified as: ',classifyNB(thisDoc,p0V,p1V,pAb))

# 文件解析函数
def textParse(bigString):    #input is big string, #output is word list
    import re
    listOfTokens = re.split(r'\W*', bigString)   # 使用正则表达式来切分句子
    return [tok.lower() for tok in listOfTokens if len(tok) > 2] # 去掉少于两个字符的字符串，并将所有字符串转化为小写

# 垃圾邮件测试函数    
def spamTest():
    import random
    # 导入并解析文本文件
    docList=[]; classList = []; fullText =[]
    for i in range(1,26):       
        wordList = textParse(open('email/spam/%d.txt' % i).read())
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(1)
        wordList = textParse(open('email/ham/%d.txt' % i).read())
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    # 创建一个包含所有文档中出现的不重复词的列表      
    vocabList = createVocabList(docList) # create vocabulary
    # 构建一个测试集与一个训练集，随机选出10封邮件作为测试集，其余的作为训练集
    trainingSet = list(range(50)); testSet=[]           # create test set
    for i in range(10):
        randIndex = int(random.uniform(0,len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])
    # 调用bagOfWords2VecMN()函数，依次生成词条向量    
    trainMat=[]; trainClasses = []
    for docIndex in trainingSet:#train the classifier (get probs) trainNB0
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        trainClasses.append(classList[docIndex])
    # 调用trainNB0()函数训练，计算属于垃圾邮件的概率，及两个类别的概率向量
    p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
    # 测试，计算分类函数的错误率
    errorCount = 0
    # 对测试集分类
    for docIndex in testSet:        #classify the remaining items
        wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
        if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:
            errorCount += 1
            print ("classification error",docList[docIndex])
    print ('the error rate is: ',float(errorCount)/len(testSet))
    #return vocabList,fullText

def calcMostFreq(vocabList,fullText):
    import operator
    freqDict = {}
    for token in vocabList:
        freqDict[token]=fullText.count(token)
    sortedFreq = sorted(freqDict.iteritems(), key=operator.itemgetter(1), reverse=True) 
    return sortedFreq[:30]       

def localWords(feed1,feed0):
    import feedparser
    docList=[]; classList = []; fullText =[]
    minLen = min(len(feed1['entries']),len(feed0['entries']))
    for i in range(minLen):
        wordList = textParse(feed1['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(1) #NY is class 1
        wordList = textParse(feed0['entries'][i]['summary'])
        docList.append(wordList)
        fullText.extend(wordList)
        classList.append(0)
    vocabList = createVocabList(docList)#create vocabulary
    top30Words = calcMostFreq(vocabList,fullText)   #remove top 30 words
    for pairW in top30Words:
        if pairW[0] in vocabList: vocabList.remove(pairW[0])
    trainingSet = range(2*minLen); testSet=[]           #create test set
    for i in range(20):
        randIndex = int(random.uniform(0,len(trainingSet)))
        testSet.append(trainingSet[randIndex])
        del(trainingSet[randIndex])  
    trainMat=[]; trainClasses = []
    for docIndex in trainingSet:#train the classifier (get probs) trainNB0
        trainMat.append(bagOfWords2VecMN(vocabList, docList[docIndex]))
        trainClasses.append(classList[docIndex])
    p0V,p1V,pSpam = trainNB0(array(trainMat),array(trainClasses))
    errorCount = 0
    for docIndex in testSet:        #classify the remaining items
        wordVector = bagOfWords2VecMN(vocabList, docList[docIndex])
        if classifyNB(array(wordVector),p0V,p1V,pSpam) != classList[docIndex]:
            errorCount += 1
    print ('the error rate is: ',float(errorCount)/len(testSet))
    return vocabList,p0V,p1V

def getTopWords(ny,sf):
    import operator
    vocabList,p0V,p1V=localWords(ny,sf)
    topNY=[]; topSF=[]
    for i in range(len(p0V)):
        if p0V[i] > -6.0 : topSF.append((vocabList[i],p0V[i]))
        if p1V[i] > -6.0 : topNY.append((vocabList[i],p1V[i]))
    sortedSF = sorted(topSF, key=lambda pair: pair[1], reverse=True)
    print ("SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**SF**")
    for item in sortedSF:
        print (item[0])
    sortedNY = sorted(topNY, key=lambda pair: pair[1], reverse=True)
    print ("NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**NY**")
    for item in sortedNY:
        print (item[0])
